package com.itheima.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.PageVo;
import com.itheima.Result;
import com.itheima.admin.dto.PageDto;

import com.itheima.admin.dto.RoleAuthDto;
import com.itheima.admin.dto.RoleDto;

import com.itheima.admin.pojo.Rolemodule;
import com.itheima.admin.service.IRoleModuleService;
import com.itheima.admin.service.IRoleService;
import com.itheima.admin.vo.RoleVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRoleModuleService roleModuleService;
    @PostMapping("/list")
    @ApiOperation("分页查询角色列表")
    public PageVo<RoleVo> queryByPage(@RequestBody PageDto pageDto){
        return roleService.queryByPage(pageDto);
    }

    @GetMapping("/all")
    @ApiOperation("查询所有角色列表")
    public List<RoleVo> queryAll(){
        return roleService.queryAll();
    }

    @PostMapping("/add")
    @ApiOperation("添加角色")
    public Result addRole(@RequestBody RoleDto roleDto){
        boolean result = roleService.addRole(roleDto);
        return new Result(result,result?"新增角色成功":"新增角色失败",null);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除角色")
    public Result deleteRole(@PathVariable("id") String id){
        boolean result = roleService.deleteRole(id);
        return new Result(result,result?"删除角色成功":"删除角色失败",null);
    }

    @PostMapping("/auth")
    @ApiOperation("角色授权")
    public Result authRole(@RequestBody RoleAuthDto roleAuthDto){
        boolean result = roleService.authRole(roleAuthDto.getRoleId(), roleAuthDto.getModuleIds());
        return new Result(result,result?"角色授权成功":"角色授权失败",null);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询角色")
    public RoleVo queryById(@PathVariable("id") String id){
        return roleService.queryById(id);
    }

    @PutMapping("/edit")
    @ApiOperation("修改角色")
    public Result updateRole(@RequestBody RoleDto roleDto){
        return roleService.updateRole(roleDto);
    }


    @ApiOperation("查询角色对应的模块")
    @GetMapping("/role/{roleId}/modules")
    public Result getModulesById(@PathVariable String roleId) {
        List<String> stringList =  roleModuleService.list(new QueryWrapper<Rolemodule>().eq("role_id",roleId)).stream().map(Rolemodule::getModuleId).collect(Collectors.toList());
        return new Result(true,"查询成功",stringList);
    }
}
